﻿using System;
using System.Linq;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using LinqKit;
using Syncfusion.Drawing;
using Syncfusion.Windows.Forms;
using Syncfusion.Windows.Forms.Grid;
using Syncfusion.Windows.Forms.Grid.Grouping;
using Syncfusion.Grouping;
using PMngr.Data;

namespace PMngr.Main
{
    public partial class WholeApproval : BaseControl
    {
        private IRepositoryFactory repositoryFactory;
        private bool CheckBoxValue = false;

        public WholeApproval()
        {
            InitializeComponent();
            //
            InitializeGridGrouping();
            //
            this.dtTo.Value = DateTime.Today;
            this.dtFrom.Value = DateTime.Today.AddDays(-7);
            // Checkbox Settings
            this.gridList.QueryCellStyleInfo += new GridTableCellStyleInfoEventHandler(gridList_QueryCellStyleInfo);
            this.gridList.SaveCellText += new Syncfusion.Windows.Forms.Grid.GridCellTextEventHandler(gridList_SaveCellText);
            this.gridList.TableControlCellClick += new GridTableControlCellClickEventHandler(gridList_TableControlCellClick);
            this.gridList.TableControlCheckBoxClick += new GridTableControlCellClickEventHandler(gridList_TableControlCheckBoxClick);
            this.gridList.TableControl.MouseUp += new MouseEventHandler(TableControl_MouseUp);            
        }

        public WholeApproval(IRepositoryFactory repositoryFactory)
            : this()
        {
            this.repositoryFactory = repositoryFactory;
        }

        public override void InitializeControls()
        {
            this.bindingSource.DataSource = null;
        }

        void TableControl_MouseUp(object sender, MouseEventArgs e)
        {
            int row, col;
            this.gridList.TableControl.PointToRowCol(new Point(e.X, e.Y), out row, out col);
            GridTableCellStyleInfo style = this.gridList.TableControl.Model[row, col];

            IMouseController controller;
            this.gridList.TableControl.MouseControllerDispatcher.HitTest(new Point(e.X, e.Y), e.Button, e.Clicks, out controller);

            if (controller != null && controller.Name == "DragGroupHeader")
            {
                if (this.gridList.TableDescriptor.GroupedColumns.Count > 0 && col == this.gridList.TableDescriptor.GroupedColumns.Count + 1)
                    this.gridList.TableControl.GetCellRenderer(row, col - this.gridList.TableDescriptor.GroupedColumns.Count).RaiseMouseUp(row, col - this.gridList.TableDescriptor.GroupedColumns.Count, e);
                else
                    this.gridList.TableControl.GetCellRenderer(row, col).RaiseMouseUp(row, col, e);
            }
        }
        
        void gridList_QueryCellStyleInfo(object sender, GridTableCellStyleInfoEventArgs e)
        {
            if (e.TableCellIdentity.TableCellType == GridTableCellType.ColumnHeaderCell && e.TableCellIdentity.Column.Name == WholeTransferModel.GetPropertyName(p => p.Checked))
            {
                e.Style.CellType = "CheckBox";
                e.Style.CellValueType = typeof(bool);
                e.Style.CellValue = CheckBoxValue;
                e.Style.ReadOnly = false;
                e.Style.CellAppearance = GridCellAppearance.Raised;
                e.Style.Enabled = true;
            }
            e.Handled = true;
        }
        void gridList_SaveCellText(object sender, Syncfusion.Windows.Forms.Grid.GridCellTextEventArgs e)
        {
            GridTableCellStyleInfo style = (GridTableCellStyleInfo)e.Style;
            if (style.Enabled && style.TableCellIdentity.TableCellType == GridTableCellType.ColumnHeaderCell)
            {
                this.CheckBoxValue = bool.Parse(e.Text);
                e.Handled = true;
            }
        }

        bool chk = false;
        ArrayList ht = new ArrayList();
        void gridList_TableControlCheckBoxClick(object sender, GridTableControlCellClickEventArgs e)
        {
            GridTableCellStyleInfo style = (GridTableCellStyleInfo)e.TableControl.GetTableViewStyleInfo(e.Inner.RowIndex, e.Inner.ColIndex);
            if (style.Enabled)
            {
                int column = this.gridList.TableModel.NameToColIndex(WholeTransferModel.GetPropertyName(p => p.Checked));
                if (style.Enabled && style.TableCellIdentity.TableCellType == GridTableCellType.ColumnHeaderCell)
                {
                    chk = (bool)this.gridList.TableModel[style.TableCellIdentity.RowIndex, column].CellValue;
                    e.TableControl.BeginUpdate();
                    foreach (Record rec in e.TableControl.Table.Records)
                    {
                        int rowIndex = e.TableControl.Table.DisplayElements.IndexOf(rec);
                        GridTableCellStyleInfo rowStyle = (GridTableCellStyleInfo)e.TableControl.GetTableViewStyleInfo(rowIndex, column);
                        
                        if (rowStyle.Enabled && !rowStyle.ReadOnly)
                            rec.SetValue(WholeTransferModel.GetPropertyName(p => p.Checked), !chk);
                    }
                    e.TableControl.EndUpdate(true);
                }             
            }
            this.gridList.TableControl.Refresh();
        }
        void gridList_TableControlCellClick(object sender, GridTableControlCellClickEventArgs e)
        {
            GridTableCellStyleInfo style = e.TableControl.Model[e.Inner.RowIndex, e.Inner.ColIndex];
            if (style.Enabled)
            {
                if (style.TableCellIdentity.TableCellType == GridTableCellType.ColumnHeaderCell && style.TableCellIdentity.Column.Name == WholeTransferModel.GetPropertyName(p => p.Checked))
                {
                    e.Inner.Cancel = true;
                }
            }
        }

        private void InitializeGridGrouping()
        {
            foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof(WholeTransferModel)))
            {
                GridColumnDescriptor gcd = new GridColumnDescriptor(pd.Name, pd.Name, WholeTransferModel.Dict[pd.Name], true, 150);
                if (pd.Name == WholeTransferModel.GetPropertyName(w => w.Description)) gcd.Width = 200;
                if (gcd.Name == WholeTransferModel.GetPropertyName(p => p.Checked))
                {
                    gcd.ReadOnly = false;
                    gcd.Width = 30;
                    gcd.Appearance.AnyRecordFieldCell.CellType = "CheckBox";
                    gcd.Appearance.AnyRecordFieldCell.CellValueType = typeof(bool);
                    gcd.Appearance.AnyRecordFieldCell.CellAppearance = GridCellAppearance.Raised;
                    gcd.Appearance.AnyRecordFieldCell.HorizontalAlignment = GridHorizontalAlignment.Center;
                }
                else
                {
                    gcd.Appearance.AnyRecordFieldCell.CellType = "Static";
                }
                this.gridList.TableDescriptor.Columns.Add(gcd);
            }
            this.gridList.TableDescriptor.Name = @"整体划转";
            this.gridList.TableDescriptor.FrozenColumn = WholeTransferModel.GetPropertyName(u => u.TransferFile);
            // hide the trivial items
            this.gridList.TableDescriptor.VisibleColumns.Remove(WholeTransferModel.GetPropertyName(p => p.Id));
            this.gridList.TableDescriptor.VisibleColumns.Remove(WholeTransferModel.GetPropertyName(p => p.ApprovalDate));
            this.gridList.TableDescriptor.VisibleColumns.Remove(WholeTransferModel.GetPropertyName(p => p.Approved));

            this.gridList.TableOptions.AllowSelection = GridSelectionFlags.Cell;
            this.gridList.TableModel.Options.ShowCurrentCellBorderBehavior = GridShowCurrentCellBorder.HideAlways;

            this.gridList.TableOptions.ColumnsMaxLengthFirstNRecords = 10;
            this.gridList.TableOptions.ColumnsMaxLengthStrategy = GridColumnsMaxLengthStrategy.FirstNRecords;
            gridList.Appearance.AnyCell.WrapText = false;
            gridList.Appearance.AnyCell.Trimming = StringTrimming.EllipsisCharacter;
            gridList.Appearance.AnyCell.HorizontalAlignment = GridHorizontalAlignment.Left;
            gridList.Appearance.AnyCell.TextMargins.Left = 3;
            this.gridList.Appearance.AlternateRecordFieldCell.Interior = new BrushInfo(Color.Gainsboro);
            this.gridList.TopLevelGroupOptions.CaptionText = Utilities.CategoryCaption;
            this.gridList.TopLevelGroupOptions.ShowAddNewRecordBeforeDetails = false;
            // 表示需尽快审批的数据
            GridConditionalFormatDescriptor conditionalFormat = new GridConditionalFormatDescriptor();
            //conditionalFormat.Appearance.AnyRecordFieldCell.ReadOnly = true;
            conditionalFormat.Appearance.AnyRecordFieldCell.Interior = new BrushInfo(Color.IndianRed);
            conditionalFormat.RecordFilters.Add(new RecordFilterDescriptor("RecordDate", new FilterCondition(FilterCompareOperator.LessThanOrEqualTo, DateTime.Today.AddDays(-3))));    
            gridList.TableDescriptor.ConditionalFormats.Add(conditionalFormat);
            //
            gridList.DataSource = bindingSource;           
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            var fileName = txtName.Text;
            var fromDate = dtFrom.Value.FromDate();
            var toDate = dtTo.Value.ToDate();

            var predicate = PredicateBuilder.True<WholeTransfer>();
            predicate = predicate.And(p => p.ApprovalDate == null);

            if (!String.IsNullOrWhiteSpace(fileName))
                predicate = predicate.And(p => p.TransferFile.Contains(fileName));
            //
            predicate = predicate.And(p => p.RecordDate >= fromDate && p.RecordDate <= toDate);

            using (var repository = repositoryFactory.CreateRepository())
            {
                var dataSource = repository.Find<WholeTransfer>(predicate.Expand()).Select(p => new WholeTransferModel
                                                                                                    {
                                                                                                        Id = p.Id,
                                                                                                        OutUnit =
                                                                                                            p.OutUnit,
                                                                                                        InUnit =
                                                                                                            p.InUnit,
                                                                                                        TransferFile =
                                                                                                            p.
                                                                                                            TransferFile,
                                                                                                        Description =
                                                                                                            p.
                                                                                                            Description,
                                                                                                        RecordDate =
                                                                                                            p.RecordDate,
                                                                                                        ApprovalDate =
                                                                                                            p.
                                                                                                            ApprovalDate
                                                                                                    });

                var result = dataSource.ToList();
                bindingSource.DataSource = result;
            }
        }

        private void ApprovalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IList<int> selecteds = new List<int>();
            foreach (Record record in this.gridList.TableControl.Table.Records)
            {
                var check = (bool)record.GetValue(WholeTransferModel.GetPropertyName(p => p.Checked));
                if (check)
                {
                    var id = (int)record.GetValue(WholeTransferModel.GetPropertyName(p => p.Id));
                    selecteds.Add(id);
                }
            }

            if (selecteds.Count > 0)
            {
                using (var repository = repositoryFactory.CreateRepository())
                {
                    var popUp = new WholeApprovalForm(repository, selecteds);
                    var result = popUp.ShowDialog(this);
                    if (DialogResult.OK == result)
                    {
                        LogWriter(String.Format(Utilities.ApprovingWholeItems, selecteds.Count));
                        btnSearch_Click(sender, e);
                    }
                }
            }
            else
            {
                MessageFactory.Show(Utilities.FirstRequired);           
            }           
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Enter)
            {
                btnSearch_Click(this, EventArgs.Empty);
                return true;
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }    

    }
}
